import 'package:flutter/material.dart';

class ScrollListener extends StatefulWidget {
  @override
  _ScrollListenerState createState() => _ScrollListenerState();
}

class _ScrollListenerState extends State<ScrollListener> {
  final ScrollController _scrollController = ScrollController();

  bool isEnd = false;
  double offset = 0;
  String notify = '';

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      setState(() {
        offset = _scrollController.offset;
        isEnd = _scrollController.position.pixels ==
            _scrollController.position.maxScrollExtent;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('ScrollListener Dome')),
      body: Container(
        child: NotificationListener(
          onNotification: (ScrollNotification notifycation) {
            String notify = '';
            if (notifycation is ScrollStartNotification) {
              // ScrollStartNotification 组件开始滚动
              notify = 'ScrollStart';
            } else if (notifycation is ScrollUpdateNotification) {
              // ScrollUpdateNotification 组件位置已经发生改变
              notify = 'ScrollUpdate';
            } else if (notifycation is ScrollNotification) {
              // UserScrollNotification 表示用户改变了他们的方向
              notify = 'UserScroll';
            } else if (notifycation is ScrollEndNotification) {
              // ScrollEndNotification 组件停止滚动
              notify = 'ScrollEnd';
            }
            setState(() {
              print(notify);
              this.notify = notify;
            });

            /// 返回值，表示是否拦截住notification，如果是true，那么notifcation到此为止；如果是false，那么notification会继续向更外层widget传递。参数ScrollNotification包含了监听到的信息
            return false;
          },
          child: ListView.builder(
            controller: _scrollController,
            itemBuilder: (context, index) {
              return Card(
                child: Container(
                  height: 60,
                  alignment: Alignment.centerLeft,
                  child: Text('Item $index'),
                ),
              );
            },
            itemCount: 100,
          ),
        ),
      ),
      persistentFooterButtons: <Widget>[
        FlatButton(
          onPressed: () {
            _scrollController.animateTo(
              0,
              duration: Duration(seconds: 1),
              curve: Curves.bounceInOut,
            );
          },
          child: Text('position: ${offset.floor()}'),
        ),
        Container(width: 0.3, height: 30.0),
        FlatButton(
          onPressed: () {},
          child: Text(notify),
        ),
        Visibility(
          visible: isEnd,
          child: FlatButton(
            onPressed: () {},
            child: Text("到达底部"),
          ),
        )
      ],
    );
  }
}
